package com.hn658.user.itf;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.hn658.base.service.api.define.enums.ResponseCode;
import com.hn658.base.util.auth.Token;
import com.hn658.base.util.exception.AuthCookieException;
import com.hn658.base.util.util.TokenMarshal;
import com.hn658.framework.cache.message.MessageCache;
import com.hn658.framework.dataaccess.pagination.GenericPage;
import com.hn658.framework.shared.exception.AccessNotAllowException;
import com.hn658.framework.shared.exception.BusinessException;
import com.hn658.framework.shared.exception.UserNotLoginException;
import com.hn658.user.appinfo.service.IAppInfoService;
import com.hn658.user.common.entity.AppInfoEO;
import com.hn658.user.common.entity.UserInfoEO;
import com.hn658.user.core.service.IUserInfoService;
import com.hn658.user.itf.vo.QueryUserInfoDTO;
import com.hn658.user.itf.vo.UserInfoDTO;
import com.hn658.user.itf.vo.UserInfoResponse;

/**
 * <p>
 * 描述：用户模块的开放服务实现
 * </p>
 * 
 * @ClassName UserServiceImpl
 * @author ztjie
 * @date 2014-8-5 下午3:14:09
 */
public class ItfUserServiceImpl implements ItfUserService {
	
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IAppInfoService appInfoService;
	
	@Autowired
	private MessageCache messageCache;

	@Override
	public UserInfoResponse findUserById(Long id) {
		UserInfoResponse response = new UserInfoResponse();
		try {
			UserInfoEO user = userInfoService.findUserByUid(id);
			if(user!=null){
				UserInfoDTO userInfo = new UserInfoDTO();
				BeanUtils.copyProperties(user, userInfo);
				response.setUserInfo(userInfo);				
			}
			response.setCode(ResponseCode.IsSuccess);
		} catch (BusinessException e) {
			response.setCode(ResponseCode.IsError);
			response.setMessage(messageCache.getMessage(e.getErrorCode()));
		}
		return response;
	}

	@Override
	public UserInfoResponse findUserByLoginAccount(String loginAccount) {
		UserInfoResponse response = new UserInfoResponse();
		try {
			UserInfoEO user = userInfoService.findUserByAccount(loginAccount);
			UserInfoDTO userInfo = new UserInfoDTO();
			BeanUtils.copyProperties(user, userInfo);
			response.setUserInfo(userInfo);
			response.setCode(ResponseCode.IsSuccess);
		} catch (BusinessException e) {
			response.setCode(ResponseCode.IsError);
			response.setMessage(messageCache.getMessage(e.getErrorCode()));
		}
		return response;
	}

	@Override
	public UserInfoResponse queryEnableUser() {
		UserInfoResponse response = new UserInfoResponse();
		try {
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("isDeleted", false);
			List<UserInfoEO> userList = userInfoService.queryAllUser(queryMap);
			List<UserInfoDTO> userInfoList = new LinkedList<UserInfoDTO>();
			for(UserInfoEO user : userList){
				UserInfoDTO userInfo = new UserInfoDTO();
				BeanUtils.copyProperties(user, userInfo);
				userInfoList.add(userInfo);
			}
			response.setUserInfoList(userInfoList);
			response.setCode(ResponseCode.IsSuccess);
		} catch (BusinessException e) {
			response.setCode(ResponseCode.IsError);
			response.setMessage(messageCache.getMessage(e.getErrorCode()));
		}
		return response;
	}

	@Override
	public UserInfoResponse validateCookie(String appKey, String cookie) {
		UserInfoResponse response = new UserInfoResponse();
		try {
			if (StringUtils.isBlank(cookie)) {
				throw new UserNotLoginException();// 用户未登录
			} else {
				try {
					cookie = URLDecoder.decode(cookie, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					throw new AuthCookieException(AuthCookieException.CookieEncodeError);
				}
				Token token = TokenMarshal.unMarshal(cookie);
				if (token == null || token.expired() || token.getUid()==null) {
					throw new UserNotLoginException();// 用户未登录
				}
				Set<String> accessAppIds = userInfoService.findUserAccessAppKeyByUid(token.getUid());
				boolean isAccess = accessAppIds.contains(appKey);
				if (!isAccess) {
					throw new AccessNotAllowException();// 用户无权限
				}
				UserInfoEO userInfoEO = userInfoService.findUserByUid(Long.valueOf(token.getUid()));
				if(userInfoEO!=null){
					UserInfoDTO userInfo = new UserInfoDTO();
					BeanUtils.copyProperties(userInfoEO, userInfo);
					response.setUserInfo(userInfo);				
				}
			}
			response.setCode(ResponseCode.IsSuccess);
		} catch (UserNotLoginException e) {
			response.setCode(ResponseCode.IsNoLogin);
			response.setMessage(messageCache.getMessage(e.getErrorCode()));
		} catch (BusinessException e) {
			response.setCode(ResponseCode.IsError);
			response.setMessage(messageCache.getMessage(e.getErrorCode()));
		}
		return response;
	}

	@Override
	public UserInfoResponse queryAppUser(Map<String,Object> queryMap,String appId, int limit,
			int start, String sortBy, boolean isAsc) {
		UserInfoResponse response = new UserInfoResponse();
		try {
			
			AppInfoEO appInfo =	appInfoService.findAppByAppId(appId);
			queryMap.put("appId", appInfo.getId());
			GenericPage<UserInfoEO> pages = userInfoService.queryAppUser(queryMap, limit, start, sortBy, isAsc);
			List<UserInfoDTO> userInfoList = new LinkedList<UserInfoDTO>();
			for(UserInfoEO user : pages.getData()){
				UserInfoDTO userInfo = new UserInfoDTO();
				BeanUtils.copyProperties(user, userInfo);
				userInfoList.add(userInfo);
			}
			response.setUserInfoList(userInfoList);
			response.setTotalCount(pages.getTotalCount());
			response.setCode(ResponseCode.IsSuccess);
		} catch (BusinessException e) {
			response.setCode(ResponseCode.IsError);
			response.setMessage(messageCache.getMessage(e.getErrorCode()));
		}
		return response;
	}
}
